// pages/editTeacher/editTeacher.js
var request = require('../../operation/operation.js')
var bxt = require('../../utils/bxt.js')
var edit = false
var teacher = null
var options = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    subjects:['语文','数学','英语'],
    subjectIndex:0,
    roles: ['任课老师','班主任'],
    roleIndex:0,
    teacher:{},
    disabled:false, // 确定按钮可用/不可用控制
    loading:false // 通信加载提示
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let role = this.data.roleIndex
    this.options = options;
    if (options.teacherSid) {
      edit = true;
      teacher = getApp().globalData.param;
      role = teacher.headTeacher
      this.initView();
    }else {
      // 添加模式
      role = this.options.role
    }

    this.setData({
      roleIndex: role
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    edit = false
    teacher = null
    options = null
  },

  bindSubjectChange:function(event) {
    this.setData( {
      subjectIndex:event.detail.value
    })
  },

  bindrRoleChange:function(event) {
    this.setData({
      roleIndex: event.detail.value
    })
  },

  onNext:function(event) {
    if (0 == event.detail.value.name.length) {
      wx.showModal({
        title: '提示',
        content: '请输入完整姓名',
        showCancel:false
      })

      return;
    }

    getApp().createFormId(event.detail.formId)

    var that = this;
    var method = 'POST', path = '/teachers', params = { 'name': event.detail.value.name, 'subject': this.data.subjects[this.data.subjectIndex], 'headTeacher': this.data.roleIndex};
    if (true == edit) {
      method = 'PUT';
      path += '/' + teacher.sid;
    }else {
      params.klassSid = this.options.klassSid;
    }
    this.setButtonLoading(true)
    request.startRequest(method, path, params, true)
      .then(res => {
        that.setButtonLoading(false);      
        var data = res.data;
        if (request.SUCCESSED == data.status) {   
          if (true == edit) {
            getApp().notificationCenter.post(bxt.BIND_ROLE_MESSAGE)
            getApp().autoBack('修改成功')
          }else {
            wx.navigateTo({
              url: '../roleFinished/roleFinished',
            })
          }
        }else {
          wx.showToast({
            title: data.msg,
            icon: 'none'
          })
        }
      }).catch(e => {
        that.setButtonLoading(false);
        wx.showToast({
          title: '绑定身份失败',
          icon: 'none'
        })
      })
  },

  /**
   * 编辑模式下初始化界面
   */
  initView:function(){
    var length = this.data.subjects.length
    var index = 0;
    for (index = 0; index < length;index++){
      if (this.data.subjects[index] == teacher.subject) {
        break;
      }
    }

    this.setData({
      'teacher': teacher,
      'subjectIndex':index,
      'edit':edit
    })
  },

  /**
   * 设置按钮状态
   */
  setButtonLoading:function(loading) {
    this.setData({
      disabled: loading,
      loading: loading
    })
  }
})